﻿using System;
using System.Text;
using System.Configuration;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;
using TidyBlog.Util;
using TidyBlog.MVC;
using TidyBlog.Entity;
using TidyBlog.BLL;
using TidyBlog.MVC.WWW.Models;

namespace TidyBlog.MVC.WWW.Controllers
{
    /// <summary>
    /// 文章管理控制器 /Manage_Article/{action}
    /// </summary>
    public class Manage_ArticleController : ManageController
    {
        /// <summary>
        /// 文章列表（搜索）
        /// </summary>
        /// <param name="title">标题关键字</param>
        /// <param name="categoryid">所属分类编号</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        public ActionResult List(string title, int? categoryid, int? page)
        {
            ViewBag.CategoryList = CategoryBLL.List(0);

            var urlParams = new Dictionary<string, string>();
            urlParams.Add("title", title);
            urlParams.Add("categoryid", categoryid.GetValueOrDefault().ToString());

            var result = ArticleBLL.List(urlParams, 15, page.GetValueOrDefault());

            var paginatorHref = new StringBuilder(Request.Path);
            paginatorHref.Append("?");
            if (urlParams.Count > 0)
            {
                foreach (var param in urlParams)
                {
                    paginatorHref.Append(param.Key);
                    paginatorHref.Append("=");
                    paginatorHref.Append(param.Value);
                    paginatorHref.Append("&");
                }
            }
            paginatorHref.Append("page={0}");

            return View(new ListWithPaginator<Article>()
            {
                SearchParams = urlParams,
                Result = result,
                ResultPaginator = new Paginator(result.CurrentPage, result.PageCount, paginatorHref.ToString())
            });
        }

        /// <summary>
        /// 创建文章界面
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            ViewBag.CategoryList = CategoryBLL.List(0);

            return View();
        }

        /// <summary>
        /// 创建文章
        /// </summary>
        /// <param name="article">文章</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(Article article)
        {
            if (ViewBag.User != null)
            {
                article.AuthorId = ViewBag.User.UserId;
                article.AuthorName = ViewBag.User.UserName;
            }
            else
            {
                article.AuthorName = String.Empty;
            }

            article.PostTime = article.PostTime.AddHours(-ViewBag.Setup.TimeZone);

            var id = ArticleBLL.Create(article);

            RespondentInfo.Success(this.ControllerContext, new OperInfo()
            {
                Message = "已添加文章《" + article.Title + "》",
                Link = Url.Action("Edit", new { id }),
                LinkText = "继续编辑"
            });

            return new EmptyResult();
        }

        /// <summary>
        /// 编辑文章界面
        /// </summary>
        /// <param name="id">文章编号</param>
        /// <returns></returns>
        public ActionResult Edit(int? id)
        {
            ViewBag.CategoryList = CategoryBLL.List(0);

            var article = ArticleBLL.Read(id.GetValueOrDefault());
            if (article == null)
            {
                throw new Exception("文章不存在");
            }

            return View(article);
        }

        /// <summary>
        /// 更新文章
        /// </summary>
        /// <param name="article">文章</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(Article article)
        {
            article.PostTime = article.PostTime.AddHours(-ViewBag.Setup.TimeZone);

            ArticleBLL.Update(article);

            RespondentInfo.Success(this.ControllerContext, new OperInfo()
            {
                Message = "已更新文章《" + article.Title + "》",
                Link = Url.Action("Edit", new { id = article.ArticleId }),
                LinkText = "继续编辑"
            });

            return new EmptyResult();
        }

        /// <summary>
        /// 删除文章
        /// </summary>
        /// <param name="id">文章编号</param>
        /// <returns></returns>
        public ActionResult Delete(int? id)
        {
            ArticleBLL.Delete(id.GetValueOrDefault());

            RespondentInfo.Success(this.ControllerContext, new OperInfo()
            {
                Message = "已删除指定文章",
                Link = Request.UrlReferrer.ToString()
            });

            return new EmptyResult();
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        public JsonResult Upload()
        {
            var file = Request.Files[0];
            var size = file.ContentLength;

            if (size > 1024000)
            {
                return Json(new
                {
                    error = 1,
                    message = "文件不能大于1M"
                });
            }

            return Json(new
            {
                error = 0,
                url = "/FileTransfer.ashx?fileName=" +
                    Path.GetFileName(FileUploader.Save(file, ConfigurationManager.AppSettings["AttachmentFolder"]))
            });
        }
    }
}
